package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.*;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_statsMapper;
import cn.com.api.resultpage.InitMyAchievementPage;
import cn.com.api.service.ApiCommonService;
import cn.com.api.service.ApiErpService;
import cn.com.api.service.ApiT_log_userService;
import cn.com.api.service.ApiT_shippingService;
import cn.com.api.service.impl.base.T_shippingServiceImplBase;
import cn.com.util.*;

/**
 * 
 **/
@Service
public class ApiT_shippingServiceImpl extends T_shippingServiceImplBase
		implements ApiT_shippingService {
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiT_statsMapper apiT_statsMapper;
	@Autowired
	private ApiCommonService apiCommonService;
	@Autowired
	private ApiT_log_userService apiT_log_userService;
	@Autowired
	private ApiErpService apiErpService;

	/**
	 * 鏂扮殑璁㈠崟-浜х敓閰嶉�浠诲姟
	 * 
	 * @param dingDan
	 */
	@Transactional
	@Override
	public void produceSendTask(ApiDingDan dingDan) {
		/**
		 * 瑕佸垽鏂鍗曠殑鐘舵�--鍗佸垎浜х敓閰嶉�浠诲姟 鏈変笁涓湴鏂瑰彲浜х敓閰嶉�浠诲姟 1-涓嬪崟閫夋嫨璐у埌浠樻锛屼笖鏄嚜钀ュ晢鍝侊紙鍟嗗鑷姩鎺ュ崟锛�-閰嶉�寰呮帴鍗�
		 * 2-涓嬪崟锛屽凡浠樻锛屼笖鏄嚜钀ュ晢鍝侊紙鍟嗗鑷姩鎺ュ崟锛�-閰嶉�寰呮帴鍗�3-涓嬪崟锛岃揣鍒颁粯娆�宸蹭粯娆撅紝---闈炶嚜钀ュ晢鍝侊紝鍟嗗鎺ュ崟锛�-閰嶉�寰呮帴鍗�
		 * 
		 * 涔熷彲鍒ゆ柇锛歞d_status=2:鍟嗗宸叉帴鍗�鏀粯鏂瑰紡锛歾f_type=3锛氳揣鍒颁粯娆�// zf_type!=3 &&
		 * zi_status=1:宸叉敮浠�
		 */
		if (dingDan != null) {
			// 鍏堝垽鏂槸鍚︽帴鍗�
			Integer dd_status = dingDan.getDd_status();
			String zf_type = dingDan.getZf_type();
			ApiT_shipping shipping = new ApiT_shipping();
			String orderId = dingDan.getTitles();
			if (!Util.isNull(dd_status) && 2 == dd_status) {// 宸叉帴鍗�
				shipping.setCreate_time(new Date());
				shipping.setOrder_id(orderId);
				shipping.setStatus(0);//寰呭垎娲�
				shipping.setShipping_price(dingDan.getSendFee());//閰嶉�璐�
				shipping.setShipping_remark(0);
				shipping.setCash_term_money(BigDecimal.ZERO);
				shipping.setOn_delivery_money(BigDecimal.ZERO);
				if(!Util.isNull(zf_type) && "3".equals(zf_type)){//璐у埌浠樻
					updateShipping(shipping,dingDan);
				} else {
					Integer zi_ststus = dingDan.getZi_status();
					if (!Util.isNull(zi_ststus) && 1 == zi_ststus) {// 宸叉敮浠�
						updateShipping(shipping,dingDan);
					}
				}
				// push notification to Sender
				// apiCommonService.autoAllocateTask();
			}
			
		}
	}

	/** 鑾峰彇閰嶉�鍛樺綋鏃ユ湁鏁堣鍗曞拰璁㈠崟鎬婚噾棰�**/
	public Map<String, Object> getShipperAccount(String user_id) {
		Map<String, Object> map = apiT_shippingMapper
				.getShipperAccount(user_id);
		return map;
	}

	/** 鑾峰彇閰嶉�鍛橀厤閫佹湇鍔¤瘎浠�**/
	public Map<String, Object> getShipperShippingRemark(String user_id) {
		Map<String, Object> map = apiT_shippingMapper
				.getShipperShippingRemark(user_id);
		return map;
	}

	@Override
	public void getMyAchievement(Map<String, String> params,
			Map<String, Object> map) {
		InitMyAchievementPage initMyAchievementPage = new InitMyAchievementPage();
		/**
		 * 闇�鏁版嵁锛氭湀绱璁㈠崟閲�銆佷粖鏃ユ柊澧�銆佺敤鎴疯瘎浠�鏈堬細鏈堢疮璁¤鍗曘�鏈�揩鐨勫揩閫掑憳鏈堣鍗曢噺銆佸噯鏃堕�杈捐鍗曢噺銆佽秴鏃惰鍗曢噺銆侀绾︽棭杈�
		 * 骞冲潎璇勫垎銆佸灏戝垎鐨勮瘎鍒嗐�1-5鏄熸暟閲�
		 */
		// 鏍规嵁鏃ユ湡鏌ヨ 2015-11 浼犲埌鏈堜唤
		String date = params.get("date");
		String u_id = params.get("u_id");

		Integer orderCount = 0;
		Integer onTimeCount = 0;
		Integer overTimeCount = 0;
		Integer aheadTimeCount = 0;
		Integer maxCount = 0;
		/** *鏄�鏁伴噺 */
		Integer oneCount = 0;
		Integer twoCount = 0;
		Integer threeCount = 0;
		Integer fourCount = 0;
		Integer fiveCount = 0;
		Integer allCount = 0;
		Integer sumScore = 0;

		String[] dateArray = date.split("-");
		if (dateArray != null && dateArray.length > 0) {
			// 鏌ヨ璁㈠崟鎬绘暟鍜�鍑嗘椂閫佽揪鏁伴噺
			Integer year = Integer.parseInt(dateArray[0]);
			String monthStr = dateArray[1];
			Integer month = 0;
			if (monthStr.indexOf("0") == 0) {
				month = Integer.parseInt(monthStr.substring(1));
			} else {
				month = Integer.parseInt(monthStr);
			}
			Map<String, Object> results = apiT_statsMapper
					.searchDateByMonthDate(year, month, u_id);
			if (results != null && results.size() > 0) {
				orderCount = Integer.parseInt(results.get("orderCount")
						.toString());
				onTimeCount = Integer.parseInt(results.get("onTimeCount")
						.toString());
				overTimeCount = Integer.parseInt(results.get("overTimeCount")
						.toString());
				aheadTimeCount = Integer.parseInt(results.get("aheadTimeCount")
						.toString());
			}

			results = apiT_statsMapper.searchFastByMonthDate(year, month);
			if (results != null && results.size() > 0) {
				maxCount = Integer.parseInt(results.get("maxCount").toString());
			}
			// --杩橀渶瑕佹煡璇㈣瘎鍒嗕俊鎭�--鏍规嵁鏃堕棿 u_id
			List<Map<String, Object>> resultsMap = apiT_shippingMapper
					.searchShippingRemarkByTimeAndUid(date, u_id);
			if (resultsMap != null && resultsMap.size() > 0) {
				for (Map<String, Object> maps : resultsMap) {
					Integer grade = Integer.parseInt(maps.get("grade")
							.toString());
					Integer count = Integer.parseInt(maps.get("count")
							.toString());
					if (1 == grade) {
						oneCount = count;
					}
					if (2 == grade) {
						twoCount = count;
					}
					if (3 == grade) {
						threeCount = count;
					}
					if (4 == grade) {
						fourCount = count;
					}
					if (5 == grade) {
						fiveCount = count;
					}
					if (grade != 0) {
						allCount = allCount + count;
						sumScore = sumScore + grade * count;
					}

				}
			}
		}
		Double score = 0.0;
		if (allCount != 0) {
			score = sumScore / (double) allCount;// 璇勫垎
		}
		
		//浠婃棩鎺ュ崟鏁伴噺
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String nowDate = dateFormat.format(new Date());
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("u_id", u_id);
		paramsMap.put("date", nowDate);
		Integer newAddCount = apiT_shippingMapper.getShippingCountByConditions(paramsMap);

		initMyAchievementPage.setAheadTimeCount(aheadTimeCount);
		initMyAchievementPage.setOnTimeCount(onTimeCount);
		initMyAchievementPage.setOverTimeCount(overTimeCount);
		initMyAchievementPage.setMonthCount(orderCount);
		initMyAchievementPage.setFastestCount(maxCount);

		initMyAchievementPage.setOneCount(oneCount);
		initMyAchievementPage.setTwoCount(twoCount);
		initMyAchievementPage.setThreeCount(threeCount);
		initMyAchievementPage.setFourCount(fourCount);
		initMyAchievementPage.setFiveCount(fiveCount);
		initMyAchievementPage.setMonthEvaluateCount(allCount);
		initMyAchievementPage.setScore(score);
		
		initMyAchievementPage.setNewAddCount(newAddCount);

		map.put("datas", initMyAchievementPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}
	
	/** 瀹㈡埛瀵归厤閫佽繘琛岃瘎浠�*/
	@Override
	public void evaluateShipping(Map<String, String> params,
			Map<String, Object> map) {
		String u_id = params.get("u_id");
		String orderId = params.get("orderId");
		Integer grade = Integer.parseInt(params.get("grade"));
		
		//鏍规嵁璁㈠崟鍙锋煡璇㈤厤閫佽褰�
		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		
		if(shipping!=null){
			shipping.setShipping_remark(grade);
			apiT_shippingMapper.updateT_shipping(shipping);
		}
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
		
	}

	/** 鐢ㄦ埛姣忔鐧诲綍锛屾煡璇㈤厤閫佹湇鍔℃湭璇勪环鐨勮鍗曞垪琛�-璐у凡閫佽揪鏈瘎浠�*/
	@Override
	public void getNoEvaluateOrdersByUser(Map<String, String> params,
			Map<String, Object> map) {
		String u_id = params.get("u_id");
		
		List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
		results = apiT_shippingMapper.getNoEvaluateOrdersByUser(u_id);
		
		map.put("datas", results);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
		
	}

	@Override
	//鏍规嵁status鐘舵�鏌ヨ璁㈠崟
	public List<ApiT_shipping> status(int status) {
		return apiT_shippingMapper.status(status);
	}

	@Override
	//閰嶉�璁㈠崟鍒楄〃
	public List<Shipping_list> htshippingsListPage(PageInfo pageInfo) {
		
		return apiT_shippingMapper.htshippingsListPage(pageInfo);
	}

	@Override
	//澶氭潯浠舵煡璇㈤厤閫佽鍗�
	public List<Shipping_list> htshippingsbytermListPage(Map<String, Object> conditions,PageInfo pageInfo) {
		return apiT_shippingMapper.htshippingsbytermListPage(conditions,pageInfo);
	}

	@Override
	//寰呮淳閫佽鍗曞垪琛�
	public List<Shipping_list> htshippingswaitListPage(PageInfo pageInfo) {
		
		return apiT_shippingMapper.htshippingswaitListPage(pageInfo);
	}

	@Override
	//澶氭潯浠舵煡璇㈠緟娲鹃�璁㈠崟
	public List<Shipping_list> htshippingwaitbytermListPage(
			Map<String, Object> conditions2,PageInfo pageInfo) {
		
		return apiT_shippingMapper.htshippingwaitbytermListPage(conditions2,pageInfo);
	}

	@Override
	//查询配送中的订单（status=1,2,3,4,5）
	public List<ApiT_shipping> shipping_ing() {
		
		return apiT_shippingMapper.shipping_ing();
	}
	
	@Override
	public void updateShipping(ApiT_shipping shipping,ApiDingDan dingDan) {
		String orderId = shipping.getOrder_id();
		ApiT_shipping shippingTemp = apiT_shippingMapper.findT_shippingByOrderId(orderId);
		if(shippingTemp==null){
			apiT_shippingMapper.insertT_shipping(shipping);
			apiCommonService.allocateOrderTask(orderId);// 浜х敓閰嶉�浠诲姟鏃讹紝鍒嗘淳閰嶉�鍛�
			//更新商品的订单下单量，购买量，销售额----在产生配送任务时记录
			apiT_log_userService.updateGoodsOrderInfo(orderId);
			//新订单抛给erp，并更新库存
			apiErpService.newOrderToErp(dingDan);
		}else{
			//也无需做更新
		}
	}

}
